import json

import requests
from PIL import Image
import base64
import io
import cv2
import numpy as np

apiUrl = "http://192.168.132.92:11025/v1/chat/completions"
apiModel = "qwen_vl"

def resize_and_encode_image(image_path):
    # 从 FileStorage 对象读取二进制数据
    file = open(image_path, 'rb')
    image_data = file.read()
    # 将二进制数据转换为 numpy 数组
    image = np.frombuffer(image_data, np.uint8)
    # 解码图像
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    # # 获取原始尺寸
    # original_height, original_width, _ = image.shape
    # # 计算缩减一半后的尺寸
    # new_width = original_width // 2
    # new_height = original_height // 2
    # # 调整图像尺寸
    # resized_image = cv2.resize(image, (new_width, new_height))
    # 将调整后的图像编码为 JPEG 格式
    _, encoded_image = cv2.imencode('.jpg', image)
    # 将编码后的图像转换为字节串
    byte_data = encoded_image.tobytes()
    # 进行 base64 编码
    base64_image = base64.b64encode(byte_data).decode('utf-8')
    # print(base64_image)
    return base64_image

def getVision(imagePath, queryText, systemText='图片信息解析'):
    # 构造请求体
    print(imagePath)
    base64_image = resize_and_encode_image(imagePath)
    messages = [
        {
            "role": "system",
            "content": [
                {
                    "type": "text",
                    "text": systemText
                }
            ]
        }, {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": queryText
                },
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/jpeg;base64,{base64_image}",
                    }
                }
            ]
        }
    ]
    return {
        "model": apiModel,
        "messages": messages,
        "stream": False,
        "max_tokens": 8192,
        "temperature": 0.7,
        "top_p": 0.7,
        "top_k": 50,
        "presence_penalty": 0,
        "frequency_penalty": 0,
    }



if __name__ == '__main__':
    # url = "http://192.168.132.92:11025/generate"
    # url = "http://192.168.132.92:11025/v1/models"
    head = {"Content-Type": "application/json"}
    data = getVision('../image/card/1.jpg', '获取图片的信息')

    # base64_str = getBase64('../image/card/1.jpg')

    # prompt = [
    #     {
    #         "type": "text",
    #         "text": "获取图片里的中文信息"
    #     },
    #     {
    #         "type": "image_url",
    #         # "image_url": "https://www.wenziyun.cn/static/welcome24/tu/tounao.jpg"
    #         "image_url": f"data:image/jpeg;base64,{base64_str}"
    #     }
    # ]
    # payload = {
    #     "prompt": prompt,
    #     "stream": False,
    #     "max_tokens": 8192,
    #     "temperature": 0.01,
    #     "top_p": 0.9,
    #     "presence_penalty": 0.5,
    #     "frequency_penalty": 0.5,
    # }
    # print(payload)
    # response = requests.post(
    #     apiUrl,
    #     headers=headers,
    #     json=data,
    #     timeout=600
    # )

    try:
        response = requests.post(apiUrl, json=data, headers=head)
        # 检查HTTP错误
        response.raise_for_status()
        result = response.json()
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
        result = None

    if result:
        # 假设响应格式为 {"choices": [{"message": {"content": "..."}}]}
        generated_text = result["choices"][0]["message"]["content"]
        print("生成的回复：\n", generated_text)

    # response = requests.get(
#         url+'/qwen_vl',
#         headers=headers,
#         timeout=600
# )
#     data = json.loads(response.text)['text']
#     print(response.text)
